{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "h2q27gKz1H20"
      },
      "source": [
        "##### Copyright 2024 The AI Edge Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "TUfAcER1oUS6"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Gb7qyhNL1yWt"
      },
      "source": [
        "# Text classification with TensorFlow Lite Model Maker"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Fw5Y7snSuG51"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/lite/models/modify/model_maker/text_classification\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/models/modify/model_maker/text_classification.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/models/modify/model_maker/text_classification.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/tensorflow/tensorflow/lite/g3doc/models/modify/model_maker/text_classification.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sr3q-gvm3cI8"
      },
      "source": [
        "The [TensorFlow Lite Model Maker library](https://www.tensorflow.org/lite/models/modify/model_maker) simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.\n",
        "\n",
        "This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used text classification model to classify movie reviews on a mobile device. The text classification model classifies text into predefined categories. The inputs should be preprocessed text and the outputs are the probabilities of the categories. The dataset used in this tutorial are positive and negative movie reviews."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bcLF2PKkSbV3"
      },
      "source": [
        "## Prerequisites\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2vvAObmTqglq"
      },
      "source": [
        "### Install the required packages\n",
        "To run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qhl8lqVamEty"
      },
      "outputs": [],
      "source": [
        "!sudo apt -y install libportaudio2\n",
        "!pip install -q tflite-model-maker\n",
        "!pip uninstall -y tflite_support_nightly\n",
        "!pip install tflite_support_nightly"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l6lRhVK9Q_0U"
      },
      "source": [
        "Import the required packages."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XtxiUeZEiXpt"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import os\n",
        "\n",
        "from tflite_model_maker import model_spec\n",
        "from tflite_model_maker import text_classifier\n",
        "from tflite_model_maker.config import ExportFormat\n",
        "from tflite_model_maker.text_classifier import AverageWordVecSpec\n",
        "from tflite_model_maker.text_classifier import DataLoader\n",
        "\n",
        "from tflite_support.task import core\n",
        "from tflite_support.task import processor\n",
        "from tflite_support.task import text\n",
        "\n",
        "import tensorflow as tf\n",
        "assert tf.__version__.startswith('2')\n",
        "tf.get_logger().setLevel('ERROR')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BRd13bfetO7B"
      },
      "source": [
        "### Download the sample training data.\n",
        "\n",
        "In this tutorial, we will use the [SST-2](https://nlp.stanford.edu/sentiment/index.html) (Stanford Sentiment Treebank) which is one of the tasks in the [GLUE](https://gluebenchmark.com/) benchmark. It contains 67,349 movie reviews for training and 872 movie reviews for testing. The dataset has two classes: positive and negative movie reviews."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "R2BSkxWg6Rhx"
      },
      "outputs": [],
      "source": [
        "data_dir = tf.keras.utils.get_file(\n",
        "      fname='SST-2.zip',\n",
        "      origin='https://dl.fbaipublicfiles.com/glue/data/SST-2.zip',\n",
        "      extract=True)\n",
        "data_dir = os.path.join(os.path.dirname(data_dir), 'SST-2')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gPYTbGrizcTC"
      },
      "source": [
        "The SST-2 dataset is stored in TSV format. The only difference between TSV and CSV is that TSV uses a tab `\\t` character as its delimiter instead of a comma `,` in the CSV format.\n",
        "\n",
        "Here are the first 5 lines of the training dataset. label=0 means negative, label=1 means positive.\n",
        "\n",
        "| sentence                                                                                  | label |   |   |   |\n",
        "|-------------------------------------------------------------------------------------------|-------|---|---|---|\n",
        "| hide new secretions from the parental units                                               | 0     |   |   |   |\n",
        "| contains no wit , only labored gags                                                       | 0     |   |   |   |\n",
        "| that loves its characters and communicates something rather beautiful about human nature  | 1     |   |   |   |\n",
        "| remains utterly satisfied to remain the same throughout                                   | 0     |   |   |   |\n",
        "| on the worst revenge-of-the-nerds clichés the filmmakers could dredge up                  | 0     |   |   |   |\n",
        "\n",
        "Next, we will load the dataset into a Pandas dataframe and change the current label names (`0` and `1`) to a more human-readable ones (`negative` and `positive`) and use them for model training.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iLNaOXnl3JQB"
      },
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "\n",
        "def replace_label(original_file, new_file):\n",
        "  # Load the original file to pandas. We need to specify the separator as\n",
        "  # '\\t' as the training data is stored in TSV format\n",
        "  df = pd.read_csv(original_file, sep='\\t')\n",
        "\n",
        "  # Define how we want to change the label name\n",
        "  label_map = {0: 'negative', 1: 'positive'}\n",
        "\n",
        "  # Excute the label change\n",
        "  df.replace({'label': label_map}, inplace=True)\n",
        "\n",
        "  # Write the updated dataset to a new file\n",
        "  df.to_csv(new_file)\n",
        "\n",
        "# Replace the label name for both the training and test dataset. Then write the\n",
        "# updated CSV dataset to the current folder.\n",
        "replace_label(os.path.join(os.path.join(data_dir, 'train.tsv')), 'train.csv')\n",
        "replace_label(os.path.join(os.path.join(data_dir, 'dev.tsv')), 'dev.csv')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xushUyZXqP59"
      },
      "source": [
        "## Quickstart\n",
        "\n",
        "There are five steps to train a text classification model:\n",
        "\n",
        "**Step 1. Choose a text classification model architecture.**\n",
        "\n",
        "Here we use the average word embedding model architecture, which will produce a small and fast model with decent accuracy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CtdZ-JDwMimd"
      },
      "outputs": [],
      "source": [
        "spec = model_spec.get('average_word_vec')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yug6gR9qyHui"
      },
      "source": [
        "Model Maker also supports other model architectures such as [BERT](https://arxiv.org/abs/1810.04805). If you are interested to learn about other architecture, see the [Choose a model architecture for Text Classifier](#scrollTo=kJ_B8fMDOhMR) section below."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s5U-A3tw6Y27"
      },
      "source": [
        "**Step 2.   Load the training and test data, then preprocess them according to a specific `model_spec`.**\n",
        "\n",
        "Model Maker can take input data in the CSV format. We will load the training and test dataset with the human-readable label name that were created earlier.\n",
        "\n",
        "Each model architecture requires input data to be processed in a particular way. `DataLoader` reads the requirement from `model_spec` and automatically executes the necessary preprocessing."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HD5BvzWe6YKa"
      },
      "outputs": [],
      "source": [
        "train_data = DataLoader.from_csv(\n",
        "      filename='train.csv',\n",
        "      text_column='sentence',\n",
        "      label_column='label',\n",
        "      model_spec=spec,\n",
        "      is_training=True)\n",
        "test_data = DataLoader.from_csv(\n",
        "      filename='dev.csv',\n",
        "      text_column='sentence',\n",
        "      label_column='label',\n",
        "      model_spec=spec,\n",
        "      is_training=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2uZkLR6N6gDR"
      },
      "source": [
        "**Step 3. Train the TensorFlow model with the training data.**\n",
        "\n",
        "The average word embedding model use `batch_size = 32` by default. Therefore you will see that it takes 2104 steps to go through the 67,349 sentences in the training dataset. We will train the model for 10 epochs, which means going through the training dataset 10 times."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kwlYdTcg63xy"
      },
      "outputs": [],
      "source": [
        "model = text_classifier.create(train_data, model_spec=spec, epochs=10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-BzCHLWJ6h7q"
      },
      "source": [
        "**Step 4. Evaluate the model with the test data.**\n",
        "\n",
        "After training the text classification model using the sentences in the training dataset, we will use the remaining 872 sentences in the test dataset to evaluate how the model performs against new data it has never seen before.\n",
        "\n",
        "As the default batch size is 32, it will take 28 steps to go through the 872 sentences in the test dataset."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8xmnl6Yy7ARn"
      },
      "outputs": [],
      "source": [
        "loss, acc = model.evaluate(test_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CgCDMe0e6jlT"
      },
      "source": [
        "**Step 5.  Export as a TensorFlow Lite model.**\n",
        "\n",
        "Let's export the text classification that we have trained in the TensorFlow Lite format. We will specify which folder to export the model.\n",
        "By default, the float TFLite model is exported for the average word embedding model architecture."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Hm_UULdW7A9T"
      },
      "outputs": [],
      "source": [
        "model.export(export_dir='average_word_vec')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rVxaf3x_7OfB"
      },
      "source": [
        "You can download the TensorFlow Lite model file using the left sidebar of Colab. Go into the `average_word_vec` folder as we specified in `export_dir` parameter above, right-click on the `model.tflite` file and choose `Download` to download it to your local computer.\n",
        "\n",
        "This model can be integrated into an Android or an iOS app using the [NLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/nl_classifier) of the [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview).\n",
        "\n",
        "See the [TFLite Text Classification sample app](https://github.com/tensorflow/examples/blob/master/lite/examples/text_classification/android/lib_task_api/src/main/java/org/tensorflow/lite/examples/textclassification/client/TextClassificationClient.java#L54) for more details on how the model is used in a working app.\n",
        "\n",
        "*Note 1: Android Studio Model Binding does not support text classification yet so please use the TensorFlow Lite Task Library.*\n",
        "\n",
        "*Note 2: There is a `model.json` file in the same folder with the TFLite model. It contains the JSON representation of the [metadata](https://www.tensorflow.org/lite/models/convert/metadata) bundled inside the TensorFlow Lite model. Model metadata helps the TFLite Task Library know what the model does and how to pre-process/post-process data for the model. You don't need to download the `model.json` file as it is only for informational purpose and its content is already inside the TFLite file.*\n",
        "\n",
        "*Note 3: If you train a text classification model using MobileBERT or BERT-Base architecture, you will need to use [BertNLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_nl_classifier) instead to integrate the trained model into a mobile app.*"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l65ctmtW7_FF"
      },
      "source": [
        "The following sections walk through the example step by step to show more details."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "izO7NU7unYot"
      },
      "source": [
        "**Step 6: Use `TFLite Task Library` to demo how to use the trained models**"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VDov6P4wppHO"
      },
      "source": [
        "Read the dev.csv file into the sentence data to predict with the trained model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XWwvHmIltQC2"
      },
      "outputs": [],
      "source": [
        "sentence_data = pd.read_csv('/content/dev.csv', index_col=0)\n",
        "sentence_data"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y_-bejm5vRBf"
      },
      "source": [
        "Model config parameter"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IAEEs3_3vPz5"
      },
      "outputs": [],
      "source": [
        "# Name of the TFLite text classification model.\n",
        "_MODEL = '/content/average_word_vec/model.tflite'\n",
        "# Whether to run the model on EdgeTPU.\n",
        "_ENABLE_EDGETPU = False\n",
        "# Number of CPU threads to run the model.\n",
        "_NUM_THREADS = 4"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bInGjRcOtQbn"
      },
      "source": [
        "Initialize model\n",
        "\n",
        "We could also change the parameters like `file_name`, `use_coral`, and `num_threads` that could affect the model results. The parameters you can adjust are:\n",
        "\n",
        "*   `file_name`: Name of the TFLite image classification model.\n",
        "*   `use_coral`: If true, inference will be delegated to a connected Coral Edge TPU device.\n",
        "*   `num_threads`: Number of CPU threads to run the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Haham4qT8hmV"
      },
      "outputs": [],
      "source": [
        "# Initialize the text classification model.\n",
        "base_options = core.BaseOptions(file_name=_MODEL, use_coral=_ENABLE_EDGETPU, num_threads=_NUM_THREADS)\n",
        "options = text.NLClassifierOptions(base_options)\n",
        "\n",
        "# Create NLClassifier from options.\n",
        "classifier = text.NLClassifier.create_from_options(options)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9HLl9LC9oA3G"
      },
      "source": [
        "Predict using `TFLite Task Library`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pAQDHFs5tTxZ"
      },
      "outputs": [],
      "source": [
        "for idx in range(20):\n",
        "  sentence = sentence_data['sentence'].iloc[idx]\n",
        "  label = sentence_data['label'].iloc[idx]\n",
        "  text_classification_result = classifier.classify(sentence)\n",
        "  classification_list = text_classification_result.classifications[0].categories\n",
        "\n",
        "  # Sort output by probability descending.\n",
        "  predict_label = sorted(\n",
        "      classification_list, key=lambda item: item.score, reverse=True)[0]\n",
        "\n",
        "  print('truth_label: {} -----\u003e predict_label: {}'.format(label, predict_label.category_name))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kJ_B8fMDOhMR"
      },
      "source": [
        "## Choose a model architecture for Text Classifier\n",
        "\n",
        "Each `model_spec` object represents a specific model for the text classifier. TensorFlow Lite Model Maker currently supports [MobileBERT](https://arxiv.org/pdf/2004.02984.pdf), averaging word embeddings and [BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) models.\n",
        "\n",
        "| Supported Model          | Name of model_spec      | Model Description                                                                                                     | Model size                                  |\n",
        "|--------------------------|-------------------------|-----------------------------------------------------------------------------------------------------------------------|---------------------------------------------|\n",
        "| Averaging Word Embedding | 'average_word_vec'      | Averaging text word embeddings with RELU activation.                                                                  |           \u003c1MB                             |\n",
        "| MobileBERT               | 'mobilebert_classifier' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device applications. | 25MB w/ quantization \u003cbr/\u003e 100MB w/o quantization                                        |\n",
        "| BERT-Base                | 'bert_classifier'       | Standard BERT model that is widely used in NLP tasks.                                                                 | 300MB |\n",
        "\n",
        "In the quick start, we have used the average word embedding model. Let's switch to [MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) to train a model with higher accuracy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vEAWuZQ1PFiX"
      },
      "outputs": [],
      "source": [
        "mb_spec = model_spec.get('mobilebert_classifier')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ygEncJxtl-nQ"
      },
      "source": [
        "## Load training data\n",
        "\n",
        "You can upload your own dataset to work through this tutorial. Upload your dataset by using the left sidebar in Colab.\n",
        "\n",
        "\u003cimg src=\"https://storage.googleapis.com/download.tensorflow.org/models/tflite/screenshots/model_maker_text_classification.png\" alt=\"Upload File\" width=\"800\" hspace=\"100\"\u003e\n",
        "\n",
        "If you prefer not to upload your dataset to the cloud, you can also locally run the library by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mWAusqz-WD5i"
      },
      "source": [
        "To keep it simple, we will reuse the SST-2 dataset downloaded earlier. Let's use the `DataLoader.from_csv` method to load the data.\n",
        "\n",
        "Please be noted that as we have changed the model architecture, we will need to reload the training and test dataset to apply the new preprocessing logic."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I_fOlZsklmlL"
      },
      "outputs": [],
      "source": [
        "train_data = DataLoader.from_csv(\n",
        "      filename='train.csv',\n",
        "      text_column='sentence',\n",
        "      label_column='label',\n",
        "      model_spec=mb_spec,\n",
        "      is_training=True)\n",
        "test_data = DataLoader.from_csv(\n",
        "      filename='dev.csv',\n",
        "      text_column='sentence',\n",
        "      label_column='label',\n",
        "      model_spec=mb_spec,\n",
        "      is_training=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MlHvVvv2hw4H"
      },
      "source": [
        "The Model Maker library also supports the `from_folder()` method to load data. It assumes that the text data of the same class are in the same subdirectory and that the subfolder name is the class name. Each text file contains one movie review sample. The `class_labels` parameter is used to specify which the subfolders."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AWuoensX4vDA"
      },
      "source": [
        "## Train a TensorFlow Model\n",
        "\n",
        "Train a text classification model using the training data.\n",
        "\n",
        "*Note: As MobileBERT is a complex model, each training epoch will takes about 10 minutes on a Colab GPU. Please make sure that you are using a GPU runtime.*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TvYSUuJY3QxR"
      },
      "outputs": [],
      "source": [
        "model = text_classifier.create(train_data, model_spec=mb_spec, epochs=3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0JKI-pNc8idH"
      },
      "source": [
        "Examine the detailed model structure."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gd7Hs8TF8n3H"
      },
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LP5FPk_tOxoZ"
      },
      "source": [
        "## Evaluate the model\n",
        "\n",
        "Evaluate the model that we have just trained using the test data and measure the loss and accuracy value."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "A8c2ZQ0J3Riy"
      },
      "outputs": [],
      "source": [
        "loss, acc = model.evaluate(test_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "esBGwHE2QxE8"
      },
      "source": [
        "## Export as a TensorFlow Lite model\n",
        "\n",
        "Convert the trained model to TensorFlow Lite model format with [metadata](https://www.tensorflow.org/lite/models/convert/metadata) so that you can later use in an on-device ML application. The label file and the vocab file are embedded in metadata. The default TFLite filename is `model.tflite`.\n",
        "\n",
        "In many on-device ML application, the model size is an important factor. Therefore, it is recommended that you apply quantize the model to make it smaller and potentially run faster.\n",
        "The default post-training quantization technique is dynamic range quantization for the BERT and MobileBERT models."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Im6wA9lK3TQB"
      },
      "outputs": [],
      "source": [
        "model.export(export_dir='mobilebert/')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w12kvDdHJIGH"
      },
      "source": [
        "The TensorFlow Lite model file can be integrated in a mobile app using the [BertNLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_nl_classifier) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview). Please note that this is **different** from the `NLClassifier` API used to integrate the text classification trained with the average word vector model architecture."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AVy0ormoMZwL"
      },
      "source": [
        "The export formats can be one or a list of the following:\n",
        "\n",
        "*   `ExportFormat.TFLITE`\n",
        "*   `ExportFormat.LABEL`\n",
        "*   `ExportFormat.VOCAB`\n",
        "*   `ExportFormat.SAVED_MODEL`\n",
        "\n",
        "By default, it exports only the TensorFlow Lite model file containing the model metadata. You can also choose to export other files related to the model for better examination. For instance, exporting only the label file and vocab file as follows:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nbK7nzK_Mfx4"
      },
      "outputs": [],
      "source": [
        "model.export(export_dir='mobilebert/', export_format=[ExportFormat.LABEL, ExportFormat.VOCAB])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HZKYthlVrTos"
      },
      "source": [
        "You can evaluate the TFLite model with `evaluate_tflite` method to measure its accuracy. Converting the trained TensorFlow model to TFLite format and apply quantization can affect its accuracy so it is recommended to evaluate the TFLite model accuracy before deployment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ochbq95ZrVFX"
      },
      "outputs": [],
      "source": [
        "accuracy = model.evaluate_tflite('mobilebert/model.tflite', test_data)\n",
        "print('TFLite model accuracy: ', accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EoWiA_zX8rxE"
      },
      "source": [
        "## Advanced Usage\n",
        "\n",
        "The `create` function is the driver function that the Model Maker library uses to create models. The `model_spec` parameter defines the model specification. The `AverageWordVecSpec` and `BertClassifierSpec` classes are currently supported. The `create` function comprises of the following steps:\n",
        "\n",
        "1. Creates the model for the text classifier according to `model_spec`.\n",
        "2. Trains the classifier model.  The default epochs and the default batch size are set by the `default_training_epochs` and `default_batch_size` variables in the `model_spec` object.\n",
        "\n",
        "This section covers advanced usage topics like adjusting the model and the training hyperparameters."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "E8VxPiOLy4Gv"
      },
      "source": [
        "### Customize the MobileBERT model hyperparameters\n",
        "\n",
        "The model parameters you can adjust are:\n",
        "\n",
        "* `seq_len`: Length of the sequence to feed into the model.\n",
        "* `initializer_range`: The standard deviation of the `truncated_normal_initializer` for initializing all weight matrices.\n",
        "* `trainable`: Boolean that specifies whether the pre-trained layer is trainable.\n",
        "\n",
        "The training pipeline parameters you can adjust are:\n",
        "\n",
        "* `model_dir`: The location of the model checkpoint files. If not set, a temporary directory will be used.\n",
        "* `dropout_rate`: The dropout rate.\n",
        "* `learning_rate`: The initial learning rate for the Adam optimizer.\n",
        "* `tpu`: TPU address to connect to.\n",
        "\n",
        "For instance, you can set the `seq_len=256` (default is 128). This allows the model to classify longer text."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4tr9BLcjy4Sh"
      },
      "outputs": [],
      "source": [
        "new_model_spec = model_spec.get('mobilebert_classifier')\n",
        "new_model_spec.seq_len = 256"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mwtiksguDfhl"
      },
      "source": [
        "### Customize the average word embedding model hyperparameters\n",
        "\n",
        "You can adjust the model infrastructure like the `wordvec_dim` and the `seq_len` variables in the `AverageWordVecSpec` class.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cAOd5_bzH9AQ"
      },
      "source": [
        "For example, you can train the model with a larger value of `wordvec_dim`. Note that you must construct a new `model_spec` if you modify the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "e9WBN0UTQoMN"
      },
      "outputs": [],
      "source": [
        "new_model_spec = AverageWordVecSpec(wordvec_dim=32)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6LSTdghTP0Cv"
      },
      "source": [
        "Get the preprocessed data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DVZurFBORG3J"
      },
      "outputs": [],
      "source": [
        "new_train_data = DataLoader.from_csv(\n",
        "      filename='train.csv',\n",
        "      text_column='sentence',\n",
        "      label_column='label',\n",
        "      model_spec=new_model_spec,\n",
        "      is_training=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tD7QVVHeRZoM"
      },
      "source": [
        "Train the new model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PzpV246_JGEu"
      },
      "outputs": [],
      "source": [
        "model = text_classifier.create(new_train_data, model_spec=new_model_spec)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LvQuy7RSDir3"
      },
      "source": [
        "### Tune the training hyperparameters\n",
        "You can also tune the training hyperparameters like `epochs` and `batch_size` that affect the model accuracy. For instance,\n",
        "\n",
        "*   `epochs`: more epochs could achieve better accuracy, but may lead to overfitting.\n",
        "*   `batch_size`: the number of samples to use in one training step.\n",
        "\n",
        "For example, you can train with more epochs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rnWFaYZBG6NW"
      },
      "outputs": [],
      "source": [
        "model = text_classifier.create(new_train_data, model_spec=new_model_spec, epochs=20)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nUaKQZBQHBQR"
      },
      "source": [
        "Evaluate the newly retrained model with 20 training epochs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BMPi1xflHDSY"
      },
      "outputs": [],
      "source": [
        "new_test_data = DataLoader.from_csv(\n",
        "      filename='dev.csv',\n",
        "      text_column='sentence',\n",
        "      label_column='label',\n",
        "      model_spec=new_model_spec,\n",
        "      is_training=False)\n",
        "\n",
        "loss, accuracy = model.evaluate(new_test_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Eq6B9lKMfhS6"
      },
      "source": [
        "### Change the Model Architecture\n",
        "\n",
        "You can change the model by changing the `model_spec`. The following shows how to change to BERT-Base model.\n",
        "\n",
        "Change the `model_spec` to BERT-Base model for the text classifier."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QfFCWrwyggrT"
      },
      "outputs": [],
      "source": [
        "spec = model_spec.get('bert_classifier')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L2d7yycrgu6L"
      },
      "source": [
        "The remaining steps are the same."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GgiD_tkyQn7l"
      },
      "source": [
        "### Customize Post-training quantization on the TensorFlow Lite model\n",
        "\n",
        "[Post-training quantization](https://www.tensorflow.org/lite/performance/post_training_quantization) is a conversion technique that can reduce model size and inference latency, while also improving CPU and hardware accelerator inference speed, with a little degradation in model accuracy. Thus, it's widely used to optimize the model.\n",
        "\n",
        "Model Maker library applies a default post-training quantization techique when exporting the model. If you want to customize post-training quantization, Model Maker supports multiple post-training quantization options using [QuantizationConfig](https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker/config/QuantizationConfig) as well. Let's take float16 quantization as an instance. First, define the quantization config.\n",
        "\n",
        "```python\n",
        "config = QuantizationConfig.for_float16()\n",
        "```\n",
        "\n",
        "\n",
        "Then we export the TensorFlow Lite model with such configuration.\n",
        "\n",
        "```python\n",
        "model.export(export_dir='.', tflite_filename='model_fp16.tflite', quantization_config=config)\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qkJGvMEx6VD-"
      },
      "source": [
        "# Read more\n",
        "\n",
        "You can read our [text classification](https://www.tensorflow.org/lite/examples/text_classification/overview) example to learn technical details. For more information, please refer to:\n",
        "\n",
        "*   TensorFlow Lite Model Maker [guide](https://www.tensorflow.org/lite/models/modify/model_maker) and [API reference](https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker).\n",
        "*  Task Library: [NLClassifier](https://www.tensorflow.org/lite/inference_with_metadata/task_library/nl_classifier) and [BertNLClassifier](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_nl_classifier) for deployment.\n",
        "*   The end-to-end reference apps: [Android](https://github.com/tensorflow/examples/tree/master/lite/examples/text_classification/android) and [iOS](https://github.com/tensorflow/examples/tree/master/lite/examples/text_classification/ios)."
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "Model Maker Text Classification Tutorial",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "gpuClass": "standard",
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
